package cn.kgm.queue;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SharedQueue {
    private static Object add = new Object();
    private static Object consumer = new Object();
    private static int queueMaxSize = 16;
    private static final List<String> queue = Collections.synchronizedList(new ArrayList<>(queueMaxSize));
    private static int queueSize = 0;
    private static boolean queuelive = false;

    public static boolean addQueue(String msg) {
        synchronized (add) {
            if (queueSize < queueMaxSize) {
                queueSize++;
                queuelive = true;
                return queue.add(msg);
            }
        }
        return (queueSize <= queueMaxSize);
    }

    public static String consumerQueue() {
        synchronized (consumer) {
            if (queuelive) {
                String msg = queue.remove(0);
                queueSize--;
                if (queueSize <= 0 && queue.size() == 0) {
                    queuelive = false;
                }
                return msg;
            }
        }
        throw new RuntimeException("quere is dead");
    }

    public static void main(String[] args) {
        createData();
        while (true) {
            System.out.println(consumerQueue());
        }
    }

    private static void createData() {
        for (int i = 0; i < 17; i++) {
            addQueue(String.valueOf(i));
        }
    }


}
